import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                           QHBoxLayout, QPushButton, QLabel)
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtCore import QTimer, Qt, QSize, QUrl
from PyQt5.QtGui import QFont, QPalette, QColor, QIcon
import winsound

STYLE_SHEET = """
QMainWindow {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #ffffff, stop:1 #f5f6fa);
}

QLabel {
    color: #2f3640;
    font-family: 'Microsoft YaHei UI';
    padding: 0;
}

#timer_display {
    font-size: 72px;
    font-weight: bold;
    background-color: rgba(0, 0, 0, 0.03);
    border-radius: 12px;
    padding: 15px 30px;
    margin: 0;
    letter-spacing: 3px;
}

#mode_label {
    font-size: 24px;
    font-weight: bold;
    color: #2f3640;
    margin: 0;
    padding: 15px 0;
    letter-spacing: 1px;
}

QPushButton {
    border: 1px solid rgba(0, 0, 0, 0.15);
    padding: 0;
    border-radius: 12px;
    width: 60px;
    height: 60px;
    max-width: 60px;
    max-height: 60px;
    margin: 5px;
    background-color: white;
}

QPushButton:hover {
    background-color: rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.25);
}

QPushButton:pressed {
    background-color: rgba(0, 0, 0, 0.1);
    padding-top: 1px;
}

QPushButton:disabled {
    background-color: #f5f5f5;
    opacity: 0.5;
    border: 1px solid rgba(0, 0, 0, 0.05);
}

#start_button {
    border-color: rgba(39, 174, 96, 0.4);
}

#start_button:hover {
    border-color: rgba(39, 174, 96, 0.6);
}

#pause_button {
    border-color: rgba(231, 76, 60, 0.4);
}

#pause_button:hover {
    border-color: rgba(231, 76, 60, 0.6);
}

#reset_button {
    border-color: rgba(52, 152, 219, 0.4);
}

#reset_button:hover {
    border-color: rgba(52, 152, 219, 0.6);
}

#mode_button {
    border-color: rgba(155, 89, 182, 0.4);
}

#mode_button:hover {
    border-color: rgba(155, 89, 182, 0.6);
}
"""

class TomatoClock(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setupTimer()
        self.setupSound()
        self.setInitialState()
        self.setupStyles()

    def setupStyles(self):
        self.setStyleSheet(STYLE_SHEET)
        
        # Set object names for specific styling
        self.timer_display.setObjectName("timer_display")
        self.mode_label.setObjectName("mode_label")
        self.start_button.setObjectName("start_button")
        self.pause_button.setObjectName("pause_button")
        self.reset_button.setObjectName("reset_button")
        self.mode_button.setObjectName("mode_button")

        # Set icons for buttons
        icon_path = os.path.join(os.path.dirname(__file__), "icons")
        icon_size = 28

        # Dictionary mapping buttons to their icon files
        button_icons = {
            self.start_button: "play.png",
            self.pause_button: "pause.png",
            self.reset_button: "reset.png",
            self.mode_button: "switch.png"
        }

        # Set icons for all buttons
        for button, icon_name in button_icons.items():
            icon_file = os.path.join(icon_path, icon_name)
            if os.path.exists(icon_file):
                button.setIcon(QIcon(icon_file))
                button.setIconSize(QSize(icon_size, icon_size))
            else:
                print(f"Warning: Icon file not found: {icon_file}")

    def initUI(self):
        # Create central widget with padding
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 10, 20, 10)
        main_layout.setSpacing(0)

        # Create container for mode label and timer
        timer_container = QWidget()
        timer_layout = QVBoxLayout(timer_container)
        timer_layout.setContentsMargins(0, 0, 0, 0)
        timer_layout.setSpacing(0)

        # Create and setup mode label
        self.mode_label = QLabel("工作时间")
        self.mode_label.setAlignment(Qt.AlignCenter)
        timer_layout.addWidget(self.mode_label)

        # Create and setup timer display
        self.timer_display = QLabel("25:00")
        self.timer_display.setAlignment(Qt.AlignCenter)
        timer_layout.addWidget(self.timer_display)

        # Add timer container to main layout
        main_layout.addWidget(timer_container)

        # Add spacing before buttons
        main_layout.addSpacing(20)

        # Create button containers
        button_container = QWidget()
        button_layout = QHBoxLayout(button_container)
        button_layout.setSpacing(10)
        button_layout.addStretch()

        # Create buttons
        self.start_button = QPushButton()
        self.pause_button = QPushButton()
        self.reset_button = QPushButton()
        self.mode_button = QPushButton()

        # Add buttons to layout with fixed size
        for button in [self.start_button, self.pause_button, 
                      self.reset_button, self.mode_button]:
            button.setFixedSize(60, 60)
            button_layout.addWidget(button)
            
        button_layout.addStretch()

        # Add button container to main layout
        main_layout.addWidget(button_container)

        # Create bottom spacing widget for vertical centering
        main_layout.addStretch(1)

        # Connect button signals
        self.start_button.clicked.connect(lambda: self.handleButtonClick(self.startTimer))
        self.pause_button.clicked.connect(lambda: self.handleButtonClick(self.pauseTimer))
        self.reset_button.clicked.connect(lambda: self.handleButtonClick(self.resetTimer))
        self.mode_button.clicked.connect(lambda: self.handleButtonClick(self.switchMode))

        # Set window properties
        self.setWindowTitle("番茄时钟")
        self.setMinimumSize(400, 320)
        self.setMaximumSize(400, 320)
        
        # Set window icon
        icon_path = os.path.join(os.path.dirname(__file__), "icons", "app_logo.ico")
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))

    def setupTimer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateDisplay)

    def setupSound(self):
        # Get default alarm sound file path
        self.alarm_file = os.path.join(os.path.dirname(__file__), "audio", "起床号.mp3")
        # Check if the audio file exists
        if not os.path.exists(self.alarm_file):
            print(f"Warning: Audio file not found at {self.alarm_file}")
        self.player = QMediaPlayer()
        self.audio = QMediaContent(QUrl.fromLocalFile(self.alarm_file))
        self.player.setMedia(self.audio)
        self.is_playing = False

    def setInitialState(self):
        self.work_time = 25 * 60  # 25 minutes in seconds
        self.break_time = 5 * 60  # 5 minutes in seconds
        self.is_work_mode = True
        self.is_running = False
        self.remaining_time = self.work_time
        self.updateDisplay()
        self.updateButtonStates()

    def startTimer(self):
        self.timer.start(1000)  # Update every second
        self.is_running = True
        self.updateButtonStates()

    def pauseTimer(self):
        self.timer.stop()
        self.is_running = False
        self.updateButtonStates()

    def resetTimer(self):
        self.timer.stop()
        self.is_running = False
        self.remaining_time = self.work_time if self.is_work_mode else self.break_time
        self.updateDisplay()
        self.updateButtonStates()

    def updateDisplay(self):
        minutes = self.remaining_time // 60
        seconds = self.remaining_time % 60
        self.timer_display.setText(f"{minutes:02d}:{seconds:02d}")
        
        if self.is_running:
            if self.remaining_time > 0:
                self.remaining_time -= 1
            else:
                self.timer.stop()
                self.is_running = False
                self.playAlarm()
                self.switchMode()

    def switchMode(self):
        self.is_work_mode = not self.is_work_mode
        self.remaining_time = self.work_time if self.is_work_mode else self.break_time
        self.mode_label.setText("工作时间" if self.is_work_mode else "休息时间")
        self.updateDisplay()
        self.updateButtonStates()

    def handleButtonClick(self, button_func):
        self.stopAlarm()
        button_func()

    def playAlarm(self):
        try:
            if os.path.exists(self.alarm_file):
                self.is_playing = True
                # winsound.PlaySound(self.alarm_file, winsound.SND_FILENAME | winsound.SND_ASYNC)
                self.player.play()
        except Exception as e:
            print(f"Warning: Could not play alarm: {e}")

    def stopAlarm(self):
        if self.is_playing:
            try:
                # winsound.PlaySound(None, winsound.SND_PURGE)
                self.player.stop()
                # Reset the player to avoid playing the sound again
                self.is_playing = False
            except Exception as e:
                print(f"Warning: Could not stop alarm: {e}")

    def updateButtonStates(self):
        self.start_button.setEnabled(not self.is_running)
        self.pause_button.setEnabled(self.is_running)
        self.reset_button.setEnabled(True)
        self.mode_button.setEnabled(not self.is_running)

        # Update window title
        mode_text = "工作" if self.is_work_mode else "休息"
        minutes = self.remaining_time // 60
        seconds = self.remaining_time % 60
        self.setWindowTitle(f"番茄时钟 - {mode_text} ({minutes:02d}:{seconds:02d})")

def main():
    app = QApplication(sys.argv)
    window = TomatoClock()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
